#include "multi.h"
#include "widget.h"
#include "ui_multi.h"

multi::multi(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::multi)
{
    ui->setupUi(this);

    crypto = new SimpleCrypt(0x6272657474667477);

    regServerSocket = new QTcpSocket(this);
    connect(regServerSocket, SIGNAL(connected()), this, SLOT(regServerConnected()));
    connect(regServerSocket, SIGNAL(readyRead()), this, SLOT(regServerRead()));
    regServerSocket->connectToHost("137.215.155.20",9077);
    while( !regServerSocket->waitForConnected(10000))
    {
        regServerSocket->connectToHost("137.215.155.20",9077);
    }
}

void multi::regServerConnected()
{
    QJsonObject json;
    json.insert("type", QJsonValue("request_server_list"));

    QJsonDocument doc(json);
    QByteArray bytes = doc.toJson();

    bytes = crypto->encryptToByteArray(bytes);

    regServerSocket->write(bytes);
    regServerSocket->waitForBytesWritten(2000);
}

void multi::regServerRead()
{
    QString str(crypto->decryptToByteArray(regServerSocket->readAll()));
    server_list = str;
    qDebug() << server_list;

    if( server_list == "")
    {
        regServerSocket->connectToHost("137.215.155.20",9077);
        regServerSocket->waitForConnected(10000);
    }
    else
    {
        updateServer(requestServerList());
    }
}

QStringList multi::requestServerList()
{
    QJsonDocument jdoc = QJsonDocument::fromJson(server_list.toUtf8());
    QJsonObject jobj = jdoc.object();

    server_ips.clear();
    server_ports.clear();
    server_names.clear();

    QJsonArray jsonArray = jobj["servers"].toArray();

    foreach (const QJsonValue & value, jsonArray)
    {
        QJsonObject obj = value.toObject();
        server_names.append(obj["name"].toString());
        server_ips.append(obj["ip"].toString());
        server_ports.append(obj["port"].toString());
    }

    return server_names;
}

multi::~multi()
{
    delete ui;
}

void multi::updateServer(QStringList list)
{
    ui->lstServer->clear();
    for (int K = 0; K < list.size(); K++)
    {
        ui->lstServer->addItem(list.at(K));
    }
}

void multi::on_btnBack_clicked()
{
    emit goback();
}

void multi::on_btnJoin_clicked()
{
    server_details.append("Human");
    // Create a client
    emit gogame();
    emit signalClient(server_details);
    // Call functions on the client
    //


}

void multi::on_btnJoinAI_clicked()
{
    server_details.append("AI");
    emit gogame();
    emit signalClient(server_details);
    // Call functions on the client
    //
}

void multi::on_lstServer_itemClicked(QListWidgetItem *item)
{
    // Create a client

    QString name = item->text();

    qDebug() << name;

    int i;
    for( i=0; i<server_names.size(); i++)
        if( server_names.at(i) == name)
            break;

    server_details.append(server_ports.at(i));
    server_details.append(server_ips.at(i));


    qDebug() << server_details;
}
